package com.example.goodpet.common;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.goodpet.R;
import com.example.goodpet.utils.UIUtils;


public abstract class LoadingPage extends FrameLayout {
    //1.定义四种状态
    public static final int STATE_loading=1;
    public static final int STATE_ERROR=2;
    public static final int STATE_EMPTY=3;
    public static final int STATE_SUCCESS=4;

    //2.定义当前状态
    private int stateCurrent=STATE_loading;//默认值

    //3.定义四种不同的界面
    private View viewLoading;
    private View viewError;
    private View viewEmpty;
    private View viewSuccess;
    private LayoutParams params;
    public LoadingPage(@NonNull Context context) {
        super(context);
        init();
    }

    public LoadingPage(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LoadingPage(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public int getStateCurrent() {
        return stateCurrent;
    }

    public void setStateCurrent(int stateCurrent) {
        this.stateCurrent = stateCurrent;
        showSafePage();
    }

    private void init() {
        params=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        if (viewLoading==null){
            viewLoading= UIUtils.getView(R.layout.page_loading);
            addView(viewLoading,params);
        }
        if (viewError==null){
            viewError= UIUtils.getView(R.layout.page_error);
            addView(viewError,params);
        }
        if (viewEmpty==null){
            viewEmpty= UIUtils.getView(R.layout.page_empty);
            addView(viewEmpty,params);
        }
        showSafePage();

    }



    private void showSafePage() {
        UIUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showPage();
            }
        });
    }

    public void showPage() {
        viewLoading.setVisibility(stateCurrent==STATE_loading?View.VISIBLE:View.INVISIBLE);
        viewError.setVisibility(stateCurrent==STATE_ERROR?View.VISIBLE:View.INVISIBLE);
        viewEmpty.setVisibility(stateCurrent==STATE_EMPTY?View.VISIBLE:View.INVISIBLE);
        if (viewSuccess==null){
            viewSuccess=UIUtils.getView(getLayoutXmlId());
            addView(viewSuccess,params);
        }
        viewSuccess.setVisibility(stateCurrent==STATE_SUCCESS?View.VISIBLE:View.INVISIBLE);
    }

    public abstract int getLayoutXmlId() ;


}
